package com.tadpole.music.view.activity.question;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.webkit.WebSettings;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.czt.mp3recorder.MP3Recorder;
import com.luck.picture.lib.tools.ScreenUtils;
import com.shuyu.waveview.AudioPlayer;
import com.shuyu.waveview.FileUtils;
import com.tadpole.music.R;
import com.tadpole.music.adapter.question.DaAnAdapter;
import com.tadpole.music.adapter.question.DrumLeftAdapter;
import com.tadpole.music.adapter.question.DrumRightAdapter;
import com.tadpole.music.bean.question.TrainingQuestionBean;
import com.tadpole.music.config.Constant;
import com.tadpole.music.config.UrlConfig;
import com.tadpole.music.iView.question.SubmitErrorQuestionIView;
import com.tadpole.music.iView.question.TrainingQuestionIView;
import com.tadpole.music.presenter.question.SubmitErrorQuestionPresenter;
import com.tadpole.music.presenter.question.TrainingQuestionPresenter;
import com.tadpole.music.utils.GuUtils;
import com.tadpole.music.utils.JsonParseUtil;
import com.tadpole.music.utils.Mutils;
import com.tadpole.music.utils.NoDoubleClickListener;
import com.tadpole.music.utils.SpUtil;
import com.tadpole.music.utils.StatusBarUtil;
import com.tadpole.music.utils.ToastUtils;
import com.tadpole.music.utils.largeImage.InputStreamBitmapDecoderFactory;
import com.tadpole.music.utils.largeImage.LargeImageView;
import com.tadpole.music.view.activity.base.BaseActivity;
import com.tadpole.music.view.activity.login.LoginActivity;
import com.tadpole.music.view.single.ErrIdSelectedSingle;
import com.tadpole.music.view.single.ErrSelectedSingle;
import com.tadpole.music.view.widget.BigImagePopup;
import com.tadpole.music.view.widget.LoginOutPopup;
import com.tadpole.music.view.widget.LollipopFixedWebView;
import com.tadpole.music.view.widget.SingleOutPopup;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * 答题
 * Created By 孙岩
 * on 2020/9/11
 */
@SuppressLint("HandlerLeak")
public class SimulationExerciseActivity extends BaseActivity implements TrainingQuestionIView, SubmitErrorQuestionIView {
    private View view_back_icon;
    //第几题
    private TextView tvCount;
    //标题
    private LollipopFixedWebView tvTitle;
    //图片
    private LargeImageView ivImage;
    //ABCD 选项
    private LinearLayout llSelect;
    //鼓
    private ImageView ivDrum;
    private LinearLayout llgu;
    //敲击按钮
    private TextView tvSend;
    //下一题
    private TextView tvNext;
    //答案
    private RelativeLayout rlAnswer;
    //答案textview
    private TextView tvAnswer;
    //答案动画
    private Animation translateAnimation;
    private LinearLayout llA;
    private LinearLayout llB;
    private LinearLayout llC;
    private LinearLayout llD;
    private TextView tvA;
    private TextView tvB;
    private TextView tvC;
    private TextView tvD;
    private ImageView ivA;
    private ImageView ivB;
    private ImageView ivC;
    private ImageView ivD;
    private TextView tvAText;
    private TextView tvBText;
    private TextView tvCText;
    private TextView tvDText;
    //录音
    private TextView tvRadio;
    //播放录音
    private TextView tvPlayRadio;
    //敲击查看答案
    private TextView tvDaAn;
    //敲击recyclerview
    private RecyclerView rvDaAn;
    private DaAnAdapter daAnAdapter;
    //获取题目
    private TrainingQuestionPresenter trainingQuestionPresenter;
    //当前页数
    private int page = 1;
    //学院id
    private String college_id;
    //等级id
    private String question_rank_id;
    //分类id
    private String question_class_id;

    //第一次进来播放的12345
    private static MediaPlayer media1;
    private static MediaPlayer media2;
    //播放text的
    private static AudioPlayer audioText;
    //有音频 播放音频的
    private static AudioPlayer player;
    //正确答案
    private int right_answer;
    //数据源
    private TrainingQuestionBean.DataBeanX bean;
    private TimeCount time;//倒计时

    //提交错题
    private SubmitErrorQuestionPresenter errorQuestionPresenter;
    //当前时间
    private long nowTime;
    //提交时间
    private long submitTime;
    //倒计时当前时间
    private BigDecimal longNow;
    //敲击的数据
    private List<String> list = new ArrayList<>();
    //服务器返回的敲击数据
    private List<String> extraList = new ArrayList<>();
    //录音路径
    private String filePath = "";
    //生成mp3的recorder
    private MP3Recorder mRecorder;
    //录音以后的播放控件
    private AudioPlayer audioPlayer;
    //web
    private WebSettings webSettings;
    //拖拽暂不支持
    private TextView tvNo;
    //录音
    private LinearLayout llLuYin;
    //点击敲击状态
    private boolean isClick = false;
    //判断录音状态
//    private boolean isRadio = false;
    //判断a的状态
    private boolean isA = false;
    private boolean isB = false;
    private boolean isC = false;
    private boolean isD = false;

    private ImageView ivPlay;
    //是否播放
    private boolean isPlay = false;
    //是否播放完成
    private boolean isPlayFinish = false;
    private String image;

    private LinearLayout llMore;

    private LinearLayout llE;
    private ImageView ivE;
    private TextView tvEText;
    private TextView tvE;

    private LinearLayout llF;
    private ImageView ivF;
    private TextView tvFText;
    private TextView tvF;

    private LinearLayout llG;
    private ImageView ivG;
    private TextView tvGText;
    private TextView tvG;

    private LinearLayout llH;
    private ImageView ivH;
    private TextView tvHText;
    private TextView tvH;

    //双鼓布局
    private LinearLayout llGuTwo;
    //鼓1
    private ImageView ivGu1;
    //鼓2
    private ImageView ivGu2;
    //鼓的答案
    private LinearLayout llTwoGu;
    //左边的答案列表
    private RecyclerView rvLeft;
    //右边的答案列表
    private RecyclerView rvRight;
    //查看答案
    private TextView tvTwoGu;

    private GuUtils guUtilsLeft;
    private GuUtils guUtilsRight;
    //是否播放完
    private boolean isFinish = false;
    private String guLeft;
    private String guRight;

    @SuppressLint("JavascriptInterface")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_simulation_exercise);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        //将头部状态栏置为透明
        StatusBarUtil.setTranslucentForImageViewInFragment(this, 0, null);

        time = new TimeCount(80000, 100);

        initViews();
        initListeners();
        college_id = getIntent().getStringExtra("college_id");
        question_rank_id = getIntent().getStringExtra("question_rank_id");
        question_class_id = getIntent().getStringExtra("question_class_id");


        trainingQuestionPresenter = new TrainingQuestionPresenter();
        trainingQuestionPresenter.attachView(this);
        trainingQuestionPresenter.getTrainingQuestion(page, college_id, question_rank_id, question_class_id, 0);

        nowTime = Mutils.getTimeStame();

        errorQuestionPresenter = new SubmitErrorQuestionPresenter();
        errorQuestionPresenter.attachView(this);

        webSettings = tvTitle.getSettings();
        webSettings.setBuiltInZoomControls(false);
        webSettings.setSupportZoom(false);

        webSettings.setDisplayZoomControls(false);
        webSettings.setJavaScriptEnabled(true);//允许使用js
        tvTitle.addJavascriptInterface(this, "Android");
        //webView 为透明
        tvTitle.setBackgroundColor(0);
    }

    //初始化控件
    private void initViews() {
        view_back_icon = findViewById(R.id.view_back_icon);
        tvCount = findViewById(R.id.tvCount);
        tvTitle = findViewById(R.id.tvTitle);
        ivImage = findViewById(R.id.ivImage);
        llSelect = findViewById(R.id.llSelect);
        ivDrum = findViewById(R.id.ivDrum);
        tvSend = findViewById(R.id.tvSend);
        tvNext = findViewById(R.id.tvNext);
        llA = findViewById(R.id.llA);
        llB = findViewById(R.id.llB);
        llC = findViewById(R.id.llC);
        llD = findViewById(R.id.llD);

        tvA = findViewById(R.id.tvA);
        tvB = findViewById(R.id.tvB);
        tvC = findViewById(R.id.tvC);
        tvD = findViewById(R.id.tvD);
        ivA = findViewById(R.id.ivA);
        ivB = findViewById(R.id.ivB);
        ivC = findViewById(R.id.ivC);
        ivD = findViewById(R.id.ivD);

        tvAText = findViewById(R.id.tvAText);
        tvBText = findViewById(R.id.tvBText);
        tvCText = findViewById(R.id.tvCText);
        tvDText = findViewById(R.id.tvDText);

        tvRadio = findViewById(R.id.tvRadio);
        rlAnswer = findViewById(R.id.rlAnswer);
        tvAnswer = findViewById(R.id.tvAnswer);
        tvPlayRadio = findViewById(R.id.tvPlayRadio);
        tvNo = findViewById(R.id.tvNo);
        llLuYin = findViewById(R.id.llLuYin);
        llgu = findViewById(R.id.llgu);
        tvDaAn = findViewById(R.id.tvDaAn);
        rvDaAn = findViewById(R.id.rvDaAn);
        ivPlay = findViewById(R.id.ivPlay);


        llMore = findViewById(R.id.llMore);
        tvEText = findViewById(R.id.tvEText);
        tvFText = findViewById(R.id.tvFText);
        tvGText = findViewById(R.id.tvGText);
        tvHText = findViewById(R.id.tvHText);
        ivE = findViewById(R.id.ivE);
        ivF = findViewById(R.id.ivF);
        ivG = findViewById(R.id.ivG);
        ivH = findViewById(R.id.ivH);
        tvE = findViewById(R.id.tvE);
        tvF = findViewById(R.id.tvF);
        tvG = findViewById(R.id.tvG);
        tvH = findViewById(R.id.tvH);
        llE = findViewById(R.id.llE);
        llF = findViewById(R.id.llF);
        llG = findViewById(R.id.llG);
        llH = findViewById(R.id.llH);

        llGuTwo = findViewById(R.id.llGuTwo);
        ivGu1 = findViewById(R.id.ivGu1);
        ivGu2 = findViewById(R.id.ivGu2);
        llTwoGu = findViewById(R.id.llTwoGu);
        rvLeft = findViewById(R.id.rvLeft);
        rvRight = findViewById(R.id.rvRight);
        tvTwoGu = findViewById(R.id.tvTwoGu);

    }

    private boolean isSelectOne = false;
    private boolean isSelectTwo = false;
    private boolean isSelectThree = false;
    private boolean isSelectFour = false;
    private boolean isSelectFive = false;
    private boolean isSelectSix = false;
    private boolean isSelectSeven = false;
    private boolean isSelectEight = false;

    private List<String> moreList = new ArrayList<>();

    //初始化监听器
    @SuppressLint("ClickableViewAccessibility")
    private void initListeners() {
        view_back_icon.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                showSingleOut();
            }
        });

        llA.setOnClickListener(new NoDoubleClickListener() {
            @SuppressLint("UseCompatLoadingForDrawables")
            @Override
            protected void onNoDoubleClick(View v) {
                if (Mutils.isNetworkAvailable()) {
                    if (bean.getData().get(0).isIs_multy_answer()) {
                        if (isSelectOne) {
                            isSelectOne = false;
                            tvA.setBackground(getResources().getDrawable(R.drawable.shape_gray_circular_line));
                        } else {
                            isSelectOne = true;
                            tvA.setBackground(getResources().getDrawable(R.drawable.shape_main_circular_solid));
                        }
                    } else {
                        setFalse();
                        isA = true;
                        tvA.setBackground(getResources().getDrawable(R.drawable.shape_main_circular_solid));
                        tvB.setBackground(getResources().getDrawable(R.drawable.shape_gray_circular_line));
                        tvC.setBackground(getResources().getDrawable(R.drawable.shape_gray_circular_line));
                        tvD.setBackground(getResources().getDrawable(R.drawable.shape_gray_circular_line));


                        if (right_answer == 1) {
                            showAnimation("恭喜您,答对了！！");
                        } else {

                            ErrIdSelectedSingle.getInstance().addWorks(bean.getData().get(0).getId());
                            ErrSelectedSingle.getInstance().addWorks(1);

                            if (right_answer == 2) {
                                showAnimation("答错了，正确答案是：B");
                            } else if (right_answer == 3) {
                                showAnimation("答错了，正确答案是：C");
                            } else if (right_answer == 4) {
                                showAnimation("答错了，正确答案是：D");
                            }
                        }
                    }
                } else {
                    ToastUtils.show("请检查您的网络设置");
                }

            }
        });

        llB.setOnClickListener(new NoDoubleClickListener() {
            @SuppressLint("UseCompatLoadingForDrawables")
            @Override
            protected void onNoDoubleClick(View v) {
                if (Mutils.isNetworkAvailable()) {
                    if (bean.getData().get(0).isIs_multy_answer()) {
                        if (isSelectTwo) {
                            isSelectTwo = false;
                            tvB.setBackground(getResources().getDrawable(R.drawable.shape_gray_circular_line));
                        } else {
                            isSelectTwo = true;
                            tvB.setBackground(getResources().getDrawable(R.drawable.shape_main_circular_solid));
                        }
                    } else {
                        setFalse();
                        isB = true;
                        tvA.setBackground(getResources().getDrawable(R.drawable.shape_gray_circular_line));
                        tvB.setBackground(getResources().getDrawable(R.drawable.shape_main_circular_solid));
                        tvC.setBackground(getResources().getDrawable(R.drawable.shape_gray_circular_line));
                        tvD.setBackground(getResources().getDrawable(R.drawable.shape_gray_circular_line));

                        if (right_answer == 2) {
                            showAnimation("恭喜您,答对了！！");
                        } else {
                            ErrIdSelectedSingle.getInstance().addWorks(bean.getData().get(0).getId());
                            ErrSelectedSingle.getInstance().addWorks(2);
                            if (right_answer == 1) {
                                showAnimation("答错了，正确答案是：A");
                            } else if (right_answer == 3) {
                                showAnimation("答错了，正确答案是：C");
                            } else if (right_answer == 4) {
                                showAnimation("答错了，正确答案是：D");
                            }

                        }
                    }
                } else {
                    ToastUtils.show("请检查您的网络设置");
                }
            }
        });

        llC.setOnClickListener(new NoDoubleClickListener() {
            @SuppressLint("UseCompatLoadingForDrawables")
            @Override
            protected void onNoDoubleClick(View v) {
                if (Mutils.isNetworkAvailable()) {
                    if (bean.getData().get(0).isIs_multy_answer()) {
                        if (isSelectThree) {
                            isSelectThree = false;
                            tvC.setBackground(getResources().getDrawable(R.drawable.shape_gray_circular_line));
                        } else {
                            isSelectThree = true;
                            tvC.setBackground(getResources().getDrawable(R.drawable.shape_main_circular_solid));
                        }
                    } else {
                        isC = true;
                        setFalse();
                        tvA.setBackground(getResources().getDrawable(R.drawable.shape_gray_circular_line));
                        tvB.setBackground(getResources().getDrawable(R.drawable.shape_gray_circular_line));
                        tvC.setBackground(getResources().getDrawable(R.drawable.shape_main_circular_solid));
                        tvD.setBackground(getResources().getDrawable(R.drawable.shape_gray_circular_line));

                        if (right_answer == 3) {
                            showAnimation("恭喜您,答对了！！");
                        } else {
                            ErrIdSelectedSingle.getInstance().addWorks(bean.getData().get(0).getId());
                            ErrSelectedSingle.getInstance().addWorks(3);
                            if (right_answer == 1) {
                                showAnimation("答错了，正确答案是：A");
                            } else if (right_answer == 2) {
                                showAnimation("答错了，正确答案是：B");
                            } else if (right_answer == 4) {
                                showAnimation("答错了，正确答案是：D");
                            }
                        }
                    }
                } else {
                    ToastUtils.show("请检查您的网络设置");
                }
            }
        });

        llD.setOnClickListener(new NoDoubleClickListener() {
            @SuppressLint("UseCompatLoadingForDrawables")
            @Override
            protected void onNoDoubleClick(View v) {
                if (Mutils.isNetworkAvailable()) {
                    if (bean.getData().get(0).isIs_multy_answer()) {
                        if (isSelectFour) {
                            isSelectFour = false;
                            tvD.setBackground(getResources().getDrawable(R.drawable.shape_gray_circular_line));
                        } else {
                            isSelectFour = true;
                            tvD.setBackground(getResources().getDrawable(R.drawable.shape_main_circular_solid));
                        }
                    } else {
                        isD = true;
                        setFalse();
                        tvA.setBackground(getResources().getDrawable(R.drawable.shape_gray_circular_line));
                        tvB.setBackground(getResources().getDrawable(R.drawable.shape_gray_circular_line));
                        tvC.setBackground(getResources().getDrawable(R.drawable.shape_gray_circular_line));
                        tvD.setBackground(getResources().getDrawable(R.drawable.shape_main_circular_solid));

                        if (right_answer == 4) {
                            showAnimation("恭喜您,答对了！！");
                        } else {
                            ErrIdSelectedSingle.getInstance().addWorks(bean.getData().get(0).getId());
                            ErrSelectedSingle.getInstance().addWorks(4);
                            if (right_answer == 1) {
                                showAnimation("答错了，正确答案是：A");
                            } else if (right_answer == 2) {
                                showAnimation("答错了，正确答案是：B");
                            } else if (right_answer == 3) {
                                showAnimation("答错了，正确答案是：C");
                            }
                        }
                    }
                } else {
                    ToastUtils.show("请检查您的网络设置");

                }
            }
        });

        llE.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                if (Mutils.isNetworkAvailable()) {
                    if (bean.getData().get(0).isIs_multy_answer()) {
                        if (isSelectFive) {
                            isSelectFive = false;
                            tvE.setBackground(getResources().getDrawable(R.drawable.shape_gray_circular_line));
                        } else {
                            isSelectFive = true;
                            tvE.setBackground(getResources().getDrawable(R.drawable.shape_main_circular_solid));
                        }
                    }
                } else {
                    ToastUtils.show("请检查您的网络设置");

                }
            }
        });

        llF.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                if (Mutils.isNetworkAvailable()) {
                    if (bean.getData().get(0).isIs_multy_answer()) {
                        if (isSelectSix) {
                            isSelectSix = false;
                            tvF.setBackground(getResources().getDrawable(R.drawable.shape_gray_circular_line));
                        } else {
                            isSelectSix = true;
                            tvF.setBackground(getResources().getDrawable(R.drawable.shape_main_circular_solid));
                        }
                    }
                } else {
                    ToastUtils.show("请检查您的网络设置");

                }
            }
        });

        llG.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                if (Mutils.isNetworkAvailable()) {
                    if (bean.getData().get(0).isIs_multy_answer()) {
                        if (isSelectSeven) {
                            isSelectSeven = false;
                            tvG.setBackground(getResources().getDrawable(R.drawable.shape_gray_circular_line));
                        } else {
                            isSelectSeven = true;
                            tvG.setBackground(getResources().getDrawable(R.drawable.shape_main_circular_solid));
                        }
                    }
                } else {
                    ToastUtils.show("请检查您的网络设置");

                }
            }
        });

        llH.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                if (Mutils.isNetworkAvailable()) {
                    if (bean.getData().get(0).isIs_multy_answer()) {
                        if (isSelectEight) {
                            isSelectEight = false;
                            tvH.setBackground(getResources().getDrawable(R.drawable.shape_gray_circular_line));
                        } else {
                            isSelectEight = true;
                            tvH.setBackground(getResources().getDrawable(R.drawable.shape_main_circular_solid));
                        }
                    }
                } else {
                    ToastUtils.show("请检查您的网络设置");

                }
            }
        });

        //下一题
        tvNext.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                if (Mutils.isNetworkAvailable()) {
                    if (tvNext.getText().toString().trim().equals("下一题")) {
                        if (bean.getData().get(0).getAnswer_type() == 1 || bean.getData().get(0).getAnswer_type() == 2 || bean.getData().get(0).getAnswer_type() == 5) {
                            if (bean.getData().get(0).isIs_multy_answer()) {
                                if (isSelectOne) {
                                    moreList.add("1");
                                }
                                if (isSelectTwo) {
                                    moreList.add("2");
                                }
                                if (isSelectThree) {
                                    moreList.add("3");
                                }
                                if (isSelectFour) {
                                    moreList.add("4");
                                }
                                if (isSelectFive) {
                                    moreList.add("5");
                                }
                                if (isSelectSix) {
                                    moreList.add("6");
                                }
                                if (isSelectSeven) {
                                    moreList.add("7");
                                }
                                if (isSelectEight) {
                                    moreList.add("8");
                                }
                                List<String> rightList = Arrays.asList(bean.getData().get(0).getMulty_right_answer().split(","));
                                if (Mutils.compare(moreList, rightList)) {
                                    ToastUtils.show("恭喜您答对了");
                                } else {
                                    if (moreList.size() != 0) {
                                        ErrIdSelectedSingle.getInstance().addWorks(bean.getData().get(0).getId());
                                        ErrSelectedSingle.getInstance().addWorks(Integer.parseInt(moreList.get(0)));
                                    }

                                }
                            } else {
                                if (!isA && !isB && !isC && !isD) {
                                    ErrIdSelectedSingle.getInstance().addWorks(bean.getData().get(0).getId());
                                    ErrSelectedSingle.getInstance().addWorks(0);
                                }
                            }
                        }
                        stopPlay();
                        trainingQuestionPresenter.getTrainingQuestion(page, college_id, question_rank_id, question_class_id, 0);
                        isPlay = false;
                        isPlayFinish = false;
                        ivPlay.setVisibility(View.GONE);
                    } else {//完成
                        if (bean.getData().get(0).getAnswer_type() == 7 || bean.getData().get(0).getAnswer_type() == 8) {//试唱模唱不提交错题
                            ToastUtils.show("答题结束");
                            SimulationExerciseActivity.this.finish();
                        } else {//其他提交
                            if (bean.getData().get(0).getAnswer_type() == 1 || bean.getData().get(0).getAnswer_type() == 2 || bean.getData().get(0).getAnswer_type() == 5) {
                                if (!isA && !isB && !isC && !isD) {
                                    ErrIdSelectedSingle.getInstance().addWorks(bean.getData().get(0).getId());
                                    ErrSelectedSingle.getInstance().addWorks(0);
                                }
                            }
                            stopPlay();
                            submitTime = Mutils.getTimeStame();
                            String time = Mutils.formatTime(submitTime - nowTime);
                            if (time.equals("0")) {
                                time = "1";
                            }

                            Log.d("sunyan", "提交答题记录" + ErrIdSelectedSingle.getInstance().getWorksList().toString());


                            errorQuestionPresenter.setErrorQuestion(
                                    1,
                                    college_id,
                                    question_rank_id,
                                    question_class_id,
                                    JsonParseUtil.ListToStr(ErrSelectedSingle.getInstance().getWorksList()),
                                    JsonParseUtil.ListToStr(ErrIdSelectedSingle.getInstance().getWorksList()),
                                    time);

                        }
                    }
                    moreList.clear();
                    isSelectOne = false;
                    isSelectTwo = false;
                    isSelectThree = false;
                    isSelectFour = false;
                    isSelectFive = false;
                    isSelectSix = false;
                    isSelectSeven = false;
                    isSelectEight = false;

                    if (tvRadio.getText().toString().equals("停止录音")) {
                        stopRecord();
                    }
                } else {
                    ToastUtils.show("请假查您的网络设置");
                }
            }
        });

        //播放按钮
        ivPlay.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                //如果正在播放 并且没播放完成 暂停
                if (isPlay && !isPlayFinish) {
                    if (player != null) {
                        player.pause();
                    }
                    isPlay = false;
                    ivPlay.setImageResource(R.mipmap.bofang);
                } else if (!isPlay && !isPlayFinish) {//如果不是正在播放 并且没播放完成 恢复
                    if (player != null) {
                        player.play();
                    }
                    isPlay = true;
                    ivPlay.setImageResource(R.mipmap.zanting);
                } else if (!isPlay && isPlayFinish) {
                    if (bean.getData().size() != 0) {
                        play(bean.getData().get(0).getBg_sound());
                    }
                }
            }
        });

        tvSend.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int action = event.getAction();
                if (action == MotionEvent.ACTION_DOWN) { // 按下
                    ivDrum.setBackgroundResource(R.mipmap.gu_down_icon);
                } else if (action == MotionEvent.ACTION_UP) { // 松开
                    ivDrum.setBackgroundResource(R.mipmap.gu_up_icon);   //切换图片
                }
                return false;
            }
        });

        //敲鼓
        tvSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                list.add(String.valueOf(new BigDecimal(80).subtract(longNow)));
            }
        });

        //开始录音
        tvRadio.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                if (tvRadio.getText().toString().trim().equals("开始录音")) {
                    startRecord();
                    tvRadio.setText("停止录音");
                    llLuYin.setVisibility(View.VISIBLE);
                    llLuYin.bringToFront();
                    tvPlayRadio.setVisibility(View.VISIBLE);
                } else if (tvRadio.getText().toString().trim().equals("停止录音")) {
                    stopRecord();
                    tvRadio.setText("录音结束");
                    tvRadio.setEnabled(false);
                    llLuYin.setVisibility(View.GONE);
                }
            }
        });


        //播放录音
        tvPlayRadio.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                if (filePath.equals("")) {
                    ToastUtils.show("请先进行录制");
                } else if (tvRadio.getText().toString().trim().equals("停止录音")) {
                    ToastUtils.show("请先点击停止录音");
                } else {
                    playInModeStream();
                }
            }
        });

        //敲鼓查看答案
        tvDaAn.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                if (Mutils.isNetworkAvailable()) {

                    if (isClick) {
                        rvDaAn.setVisibility(View.VISIBLE);
                        GridLayoutManager layoutManager = new GridLayoutManager(SimulationExerciseActivity.this, 7);
                        rvDaAn.setLayoutManager(layoutManager);
                        //创建适配器
                        daAnAdapter = new DaAnAdapter(SimulationExerciseActivity.this, list, extraList);
                        //给RecyclerView设置适配器
                        rvDaAn.setAdapter(daAnAdapter);
                        rvDaAn.setNestedScrollingEnabled(false);
                    } else {
                        ToastUtils.show("请等待音乐播放完成再查看答案");
                    }

                } else {
                    ToastUtils.show("请检查您的网络设置");
                }
            }
        });

        ivImage.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                ArrayList<String> a = new ArrayList<>();
                a.add(image);
                BigImagePopup bigImagePopup = new BigImagePopup(SimulationExerciseActivity.this, 0, a);
                bigImagePopup.showPopupWindow();
            }
        });

        //鼓1的敲击
        ivGu1.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (isFinish) {
                    int action = event.getAction();
                    if (action == MotionEvent.ACTION_DOWN) { // 按下
                        ivGu1.setBackgroundResource(R.mipmap.gu_down_icon);
                    } else if (action == MotionEvent.ACTION_UP) { // 松开
                        ivGu1.setBackgroundResource(R.mipmap.gu_up_icon);   //切换图片
                    }
                } else {
                    ToastUtils.show("请等待题目播放完成再进行击鼓");
                }

                return false;
            }
        });

        //记录鼓1的敲击集合
        ivGu1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isFinish) {
                    guUtilsLeft.drum(Mutils.getTimeStame());
                } else {
                    ToastUtils.show("请等待题目播放完成再进行击鼓");
                }
            }
        });

        //鼓2的敲击
        ivGu2.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (isFinish) {
                    int action = event.getAction();
                    if (action == MotionEvent.ACTION_DOWN) { // 按下
                        ivGu2.setBackgroundResource(R.mipmap.gu_down_icon);
                    } else if (action == MotionEvent.ACTION_UP) { // 松开
                        ivGu2.setBackgroundResource(R.mipmap.gu_up_icon);   //切换图片
                    }
                } else {
                    ToastUtils.show("请等待题目播放完成再进行击鼓");
                }
                return false;
            }
        });

        //记录鼓2的敲击集合
        ivGu2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isFinish) {
//                    gu2List.add(String.valueOf(new BigDecimal(80).subtract(longNow)));
                    guUtilsRight.drum(Mutils.getTimeStame());
                } else {
                    ToastUtils.show("请等待题目播放完成再进行击鼓");
                }
            }
        });

        //查看是双鼓的答案
        tvTwoGu.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                if (Mutils.isNetworkAvailable()) {

                    if (isClick) {
                        llTwoGu.setVisibility(View.VISIBLE);

                        GridLayoutManager layoutManager = new GridLayoutManager(SimulationExerciseActivity.this, 7);
                        rvLeft.setLayoutManager(layoutManager);
                        //创建适配器
                        DrumLeftAdapter drumLeftAdapter = new DrumLeftAdapter(SimulationExerciseActivity.this, guUtilsLeft.getResultList());
                        //给RecyclerView设置适配器
                        rvLeft.setAdapter(drumLeftAdapter);
                        rvLeft.setNestedScrollingEnabled(false);


                        GridLayoutManager layoutManager2 = new GridLayoutManager(SimulationExerciseActivity.this, 7);
                        rvRight.setLayoutManager(layoutManager2);
                        //创建适配器
                        DrumRightAdapter drumRightAdapter = new DrumRightAdapter(SimulationExerciseActivity.this,guUtilsRight.getResultList());
                        //给RecyclerView设置适配器
                        rvRight.setAdapter(drumRightAdapter);
                        rvRight.setNestedScrollingEnabled(false);

                    } else {
                        ToastUtils.show("请等待音乐播放完成再查看答案");
                    }

                } else {
                    ToastUtils.show("请检查您的网络设置");
                }
            }
        });
    }


    //选择以后的状态
    private void setFalse() {
        llA.setEnabled(false);
        llB.setEnabled(false);
        llC.setEnabled(false);
        llD.setEnabled(false);
    }

    //选择前的状态
    @SuppressLint("UseCompatLoadingForDrawables")
    private void setTrue() {
        llA.setEnabled(true);
        llB.setEnabled(true);
        llC.setEnabled(true);
        llD.setEnabled(true);

        tvA.setBackground(getResources().getDrawable(R.drawable.shape_gray_circular_line));
        tvB.setBackground(getResources().getDrawable(R.drawable.shape_gray_circular_line));
        tvC.setBackground(getResources().getDrawable(R.drawable.shape_gray_circular_line));
        tvD.setBackground(getResources().getDrawable(R.drawable.shape_gray_circular_line));
        tvE.setBackground(getResources().getDrawable(R.drawable.shape_gray_circular_line));
        tvF.setBackground(getResources().getDrawable(R.drawable.shape_gray_circular_line));
        tvG.setBackground(getResources().getDrawable(R.drawable.shape_gray_circular_line));
        tvH.setBackground(getResources().getDrawable(R.drawable.shape_gray_circular_line));
    }

    //未购买
    @Override
    public void goToPay() {
        ToastUtils.show("未购买");
    }

    //题的回调

    @RequiresApi(api = Build.VERSION_CODES.N)
    @SuppressLint({"SetTextI18n", "CheckResult"})
    @Override
    public void showQuestion(final TrainingQuestionBean.DataBeanX bean) {
        if (bean.getData() == null || bean.getData().size() == 0) {

        } else {
            RequestOptions requestOptions = new RequestOptions()
                    .priority(Priority.HIGH)
                    .diskCacheStrategy(DiskCacheStrategy.ALL);


            tvRadio.setText("开始录音");
            tvRadio.setEnabled(true);
            //敲击的list置为空
            list.clear();
            //播放录音设为GONE
            tvPlayRadio.setVisibility(View.GONE);
            llLuYin.setVisibility(View.GONE);
            rvDaAn.setVisibility(View.GONE);

            setTrue();

            rlAnswer.setAnimation(null);
            rlAnswer.setVisibility(View.GONE);
            this.bean = bean;

            if (bean.getCurrent_page() == bean.getLast_page()) {
                tvNext.setText("完成");
            }

            //页数
            page = bean.getCurrent_page() + 1;

            //双鼓 左鼓
            guUtilsLeft = new GuUtils();
            //双鼓 右鼓
            guUtilsRight = new GuUtils();

            guLeft = bean.getData().get(0).getLeft_drum();
            guRight = bean.getData().get(0).getRight_drum();

            llA.setVisibility(View.VISIBLE);
            llB.setVisibility(View.VISIBLE);
            llC.setVisibility(View.VISIBLE);
            llD.setVisibility(View.VISIBLE);

            isA = false;
            isB = false;
            isC = false;
            isD = false;

            if (bean.getData().get(0).getAnswer_type() == 1) {//文字

                llSelect.setVisibility(View.VISIBLE);

                if (bean.getData().get(0).isIs_multy_answer()) {//多选
                    llMore.setVisibility(View.VISIBLE);
                    llE.setVisibility(View.VISIBLE);
                    llF.setVisibility(View.VISIBLE);
                    llG.setVisibility(View.VISIBLE);
                    llH.setVisibility(View.VISIBLE);
                    llGuTwo.setVisibility(View.GONE);

                    if (bean.getData().get(0).getAnswer_e().equals("")) {
                        llE.setVisibility(View.GONE);
                    }
                    if (bean.getData().get(0).getAnswer_f().equals("")) {
                        llF.setVisibility(View.GONE);
                    }
                    if (bean.getData().get(0).getAnswer_g().equals("")) {
                        llG.setVisibility(View.GONE);
                    }
                    if (bean.getData().get(0).getAnswer_h().equals("")) {
                        llH.setVisibility(View.GONE);
                    }

                } else {
                    llMore.setVisibility(View.GONE);
                }

                ivA.setVisibility(View.GONE);
                ivB.setVisibility(View.GONE);
                ivC.setVisibility(View.GONE);
                ivD.setVisibility(View.GONE);
                ivE.setVisibility(View.GONE);
                ivF.setVisibility(View.GONE);
                ivG.setVisibility(View.GONE);
                ivH.setVisibility(View.GONE);

                tvAText.setVisibility(View.VISIBLE);
                tvBText.setVisibility(View.VISIBLE);
                tvCText.setVisibility(View.VISIBLE);
                tvDText.setVisibility(View.VISIBLE);
                tvEText.setVisibility(View.VISIBLE);
                tvFText.setVisibility(View.VISIBLE);
                tvGText.setVisibility(View.VISIBLE);
                tvHText.setVisibility(View.VISIBLE);

                ivDrum.setVisibility(View.GONE);
                tvSend.setVisibility(View.GONE);
                llgu.setVisibility(View.GONE);
                tvRadio.setVisibility(View.GONE);
                tvNo.setVisibility(View.GONE);
                llGuTwo.setVisibility(View.GONE);

                tvAText.setText(bean.getData().get(0).getAnswer_a());
                tvBText.setText(bean.getData().get(0).getAnswer_b());
                tvCText.setText(bean.getData().get(0).getAnswer_c());
                tvDText.setText(bean.getData().get(0).getAnswer_d());
                tvEText.setText(bean.getData().get(0).getAnswer_e());
                tvFText.setText(bean.getData().get(0).getAnswer_f());
                tvGText.setText(bean.getData().get(0).getAnswer_g());
                tvHText.setText(bean.getData().get(0).getAnswer_h());
                if (bean.getData().get(0).getAnswer_c().equals("")) {
                    llC.setVisibility(View.GONE);
                }
                if (bean.getData().get(0).getAnswer_d().equals("")) {
                    llD.setVisibility(View.GONE);
                }

            } else if (bean.getData().get(0).getAnswer_type() == 2 || bean.getData().get(0).getAnswer_type() == 5) {//图片
                llSelect.setVisibility(View.VISIBLE);

                if (bean.getData().get(0).isIs_multy_answer()) {//多选
                    llMore.setVisibility(View.VISIBLE);
                    llE.setVisibility(View.VISIBLE);
                    llF.setVisibility(View.VISIBLE);
                    llG.setVisibility(View.VISIBLE);
                    llH.setVisibility(View.VISIBLE);
                    if (bean.getData().get(0).getAnswer_e().equals("")) {
                        llE.setVisibility(View.GONE);
                    }
                    if (bean.getData().get(0).getAnswer_f().equals("")) {
                        llF.setVisibility(View.GONE);
                    }
                    if (bean.getData().get(0).getAnswer_g().equals("")) {
                        llG.setVisibility(View.GONE);
                    }
                    if (bean.getData().get(0).getAnswer_h().equals("")) {
                        llH.setVisibility(View.GONE);
                    }

                } else {
                    llMore.setVisibility(View.GONE);
                }

                ivA.setVisibility(View.VISIBLE);
                ivB.setVisibility(View.VISIBLE);
                ivC.setVisibility(View.VISIBLE);
                ivD.setVisibility(View.VISIBLE);
                ivE.setVisibility(View.VISIBLE);
                ivF.setVisibility(View.VISIBLE);
                ivG.setVisibility(View.VISIBLE);
                ivH.setVisibility(View.VISIBLE);

                tvAText.setVisibility(View.GONE);
                tvBText.setVisibility(View.GONE);
                tvCText.setVisibility(View.GONE);
                tvDText.setVisibility(View.GONE);
                tvEText.setVisibility(View.GONE);
                tvFText.setVisibility(View.GONE);
                tvGText.setVisibility(View.GONE);
                tvHText.setVisibility(View.GONE);

                ivDrum.setVisibility(View.GONE);
                tvSend.setVisibility(View.GONE);
                llgu.setVisibility(View.GONE);
                tvRadio.setVisibility(View.GONE);
                tvNo.setVisibility(View.GONE);
                llGuTwo.setVisibility(View.GONE);

                Glide.with(this).load(Constant.IMAGE_HEAD + bean.getData().get(0).getAnswer_a()).apply(requestOptions).into(ivA);
                Glide.with(this).load(Constant.IMAGE_HEAD + bean.getData().get(0).getAnswer_b()).apply(requestOptions).into(ivB);
                Glide.with(this).load(Constant.IMAGE_HEAD + bean.getData().get(0).getAnswer_c()).apply(requestOptions).into(ivC);
                Glide.with(this).load(Constant.IMAGE_HEAD + bean.getData().get(0).getAnswer_d()).apply(requestOptions).into(ivD);
                Glide.with(this).load(Constant.IMAGE_HEAD + bean.getData().get(0).getAnswer_e()).apply(requestOptions).into(ivE);
                Glide.with(this).load(Constant.IMAGE_HEAD + bean.getData().get(0).getAnswer_f()).apply(requestOptions).into(ivF);
                Glide.with(this).load(Constant.IMAGE_HEAD + bean.getData().get(0).getAnswer_g()).apply(requestOptions).into(ivG);
                Glide.with(this).load(Constant.IMAGE_HEAD + bean.getData().get(0).getAnswer_h()).apply(requestOptions).into(ivH);
                if (bean.getData().get(0).getAnswer_c().equals("")) {
                    llC.setVisibility(View.GONE);
                }
                if (bean.getData().get(0).getAnswer_d().equals("")) {
                    llD.setVisibility(View.GONE);
                }
            } else if (bean.getData().get(0).getAnswer_type() == 4 || bean.getData().get(0).getAnswer_type() == 9) {
                tvNo.setVisibility(View.VISIBLE);
                llSelect.setVisibility(View.GONE);
                ivDrum.setVisibility(View.GONE);
                tvSend.setVisibility(View.GONE);
                llgu.setVisibility(View.GONE);
                tvRadio.setVisibility(View.GONE);
                llGuTwo.setVisibility(View.GONE);
            } else if (bean.getData().get(0).getAnswer_type() == 3) {//单敲鼓
                llSelect.setVisibility(View.GONE);
                ivDrum.setVisibility(View.VISIBLE);
                llgu.setVisibility(View.VISIBLE);
                tvRadio.setVisibility(View.GONE);
                tvNo.setVisibility(View.GONE);
                llGuTwo.setVisibility(View.GONE);
                ivDrum.setBackgroundResource(R.mipmap.gu_up_icon);
                isClick = false;
            } else if (bean.getData().get(0).getAnswer_type() == 7 || bean.getData().get(0).getAnswer_type() == 8) {//视唱 模唱
                llSelect.setVisibility(View.GONE);
                ivDrum.setVisibility(View.GONE);
                tvSend.setVisibility(View.GONE);
                llgu.setVisibility(View.GONE);
                tvRadio.setVisibility(View.VISIBLE);
                tvNo.setVisibility(View.GONE);
                llGuTwo.setVisibility(View.GONE);
            } else if (bean.getData().get(0).getAnswer_type() == 10) {//敲鼓题（两个鼓）
                tvNo.setVisibility(View.GONE);
                llSelect.setVisibility(View.GONE);
                ivDrum.setVisibility(View.GONE);
                tvSend.setVisibility(View.GONE);
                llgu.setVisibility(View.GONE);
                tvRadio.setVisibility(View.GONE);
                llGuTwo.setVisibility(View.VISIBLE);
                llTwoGu.setVisibility(View.GONE);
                ivGu1.setBackgroundResource(R.mipmap.gu_up_icon);
                ivGu2.setBackgroundResource(R.mipmap.gu_up_icon);
                isClick = false;
            }

            //播放音频
            new Thread(
                    new Runnable() {
                        @Override
                        public void run() {
                            try {
                                if (bean.getData().get(0).getAnswer_type() != 4) {
                                    Thread.sleep(1000);
                                    playAuDio((page - 2), bean.getData().get(0).getTitle_sound(), bean.getData().get(0).getBg_sound(), bean.getData().get(0).getAnswer_type(), bean.getData().get(0).getPlay_times());
                                }
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
            ).start();

            String extra = bean.getData().get(0).getExtra();

            //单鼓
            extraList = Arrays.asList(extra.split(","));

            //第几题
            tvCount.setText("第" + bean.getCurrent_page() + "题");
            //正确题
            this.right_answer = bean.getData().get(0).getRight_answer();
            if (bean.getData().get(0).getTitle_img().equals("")) {
                ivImage.setVisibility(View.GONE);
            } else {
                ivImage.setVisibility(View.VISIBLE);

                image = Constant.IMAGE_HEAD + bean.getData().get(0).getTitle_img();
                Glide.with(this).load(Constant.IMAGE_HEAD + bean.getData().get(0).getTitle_img()).downloadOnly(new SimpleTarget<File>() {

                    @Override
                    public void onResourceReady(final File resource, Transition<? super File> transition) {

                        try {
                            //主线程
                            ivImage.setImage(new InputStreamBitmapDecoderFactory(new FileInputStream(resource)));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
            }

            String url = UrlConfig.getTitle + "q_type=question&id=" + bean.getData().get(0).getId();
//            Log.d("sunyan", url);

            tvTitle.loadUrl(url);
        }
    }

    @Override
    public void go401() {
        this.finish();
        Intent intent = new Intent(SimulationExerciseActivity.this, LoginActivity.class);
        startActivity(intent);
        SpUtil.getInstance(this).putString(Constant.TOKEN, "");
    }

    /**
     * 播放音频
     *
     * @param title_sound 题目音频
     * @param bg_sound    内容音频
     */
    private void playAuDio(int index, final String title_sound, final String bg_sound, final int state, final int play_time) {
        //播放本地123456
        media1 = MediaPlayer.create(SimulationExerciseActivity.this, redia(index));
        media1.start();
        if (media1 != null) {
            media1.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    if (audioText != null) {
                        audioText.pause();
                        audioText.stop();
                    }
                    if (title_sound.equals("")) {
                        playWork(bg_sound, state, play_time);
                    } else {
                        audioText = new AudioPlayer(SimulationExerciseActivity.this, new Handler() {
                            @Override
                            public void handleMessage(Message msg) {
                                super.handleMessage(msg);
                                switch (msg.what) {
                                    case AudioPlayer.HANDLER_CUR_TIME://更新的时间
                                        break;
                                    case AudioPlayer.HANDLER_COMPLETE://text播放结束
                                        playWork(bg_sound, state, play_time);
                                        break;
                                    case AudioPlayer.HANDLER_PREPARED://播放开始
                                        break;
                                    case AudioPlayer.HANDLER_ERROR://播放错误

                                        break;
                                }

                            }
                        });
                        audioText.playUrl(Constant.IMAGE_HEAD + title_sound);
                    }
                }
            });
        }

    }

    //播放网络  count 当前播放到第几遍
    @SuppressLint("HandlerLeak")
    private void playWork(final String urlMusic, final int status, final int play_time) {
        if (urlMusic.equals("")) {

        } else {
            if (status == 3 || status == 10) {//如果状态是3 说明是敲鼓 播放一遍
                if (player != null) {
                    player.pause();
                    player.stop();
                }
                player = new AudioPlayer(SimulationExerciseActivity.this, new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        super.handleMessage(msg);
                        switch (msg.what) {
                            case AudioPlayer.HANDLER_CUR_TIME://更新的时间
                                break;
                            case AudioPlayer.HANDLER_COMPLETE://播放结束
                                time.cancel();
                                tvSend.setEnabled(false);
                                isFinish = false;
                                isClick = true;
                                break;
                            case AudioPlayer.HANDLER_PREPARED://播放开始

                                guUtilsLeft.initDrum(guLeft);
                                guUtilsRight.initDrum(guRight);


                                time.start();
                                tvSend.setEnabled(true);
                                isFinish = true;
                                ToastUtils.show("开始敲击");
                                break;
                            case AudioPlayer.HANDLER_ERROR://播放错误
                                break;
                        }

                    }
                });
                player.playUrl(Constant.IMAGE_HEAD + urlMusic);

            } else {

                playMusicCount(1, play_time, urlMusic);
            }
        }
    }

    //播放第几遍

    /**
     * @param count     当前播放的第几遍
     * @param play_time 总共几遍
     * @param urlMusic  音乐数据
     */
    private void playMusicCount(final int count, final int play_time, final String urlMusic) {
        //播放
        media2 = MediaPlayer.create(SimulationExerciseActivity.this, rediaCount(count));
        media2.start();
        media2.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                playMusic(count, play_time, urlMusic);
            }
        });
    }


    //播放
    private void playMusic(final int count, final int play_time, final String urlMusic) {
        if (player != null) {
            player.pause();
            player.stop();
        }

        player = new AudioPlayer(SimulationExerciseActivity.this, new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case AudioPlayer.HANDLER_CUR_TIME://更新的时间
                        break;
                    case AudioPlayer.HANDLER_COMPLETE://播放结束

                        ivPlay.setImageResource(R.mipmap.bofang);
                        isPlayFinish = true;
                        isPlay = false;

                        if (play_time == 2 && count == 1) {
                            playMusicCount(2, play_time, urlMusic);
                        } else if (play_time == 4 && count == 1) {
                            playMusicCount(2, play_time, urlMusic);
                        } else if (play_time == 4 && count == 2) {
                            playMusicCount(3, play_time, urlMusic);
                        } else if (play_time == 4 && count == 3) {
                            playMusicCount(4, play_time, urlMusic);
                        } else {

                        }

                        break;
                    case AudioPlayer.HANDLER_PREPARED://播放开始
                        ivPlay.setVisibility(View.VISIBLE);
                        isPlay = true;
                        ivPlay.setImageResource(R.mipmap.zanting);
                        break;
                    case AudioPlayer.HANDLER_ERROR://播放错误
                        break;
                }

            }
        });
        player.playUrl(Constant.IMAGE_HEAD + urlMusic);
    }

    //第一遍 第二遍
    private int rediaCount(int index) {
        int redia = 0;
        switch (index) {
            case 1:
                redia = R.raw.to1;
                break;
            case 2:
                redia = R.raw.to2;
                break;
            case 3:
                redia = R.raw.to3;
                break;
            case 4:
                redia = R.raw.to4;
                break;
        }
        return redia;
    }


    //播放本地12345
    private int redia(int index) {
        int redia = 0;

        switch (index) {
            case 0:
                redia = R.raw.redia1;
                break;
            case 1:
                redia = R.raw.redia2;
                break;
            case 2:
                redia = R.raw.redia3;
                break;
            case 3:
                redia = R.raw.redia4;
                break;
            case 4:
                redia = R.raw.redia5;
                break;
            case 5:
                redia = R.raw.redia6;
                break;
            case 6:
                redia = R.raw.redia7;
                break;
            case 7:
                redia = R.raw.redia8;
                break;
            case 8:
                redia = R.raw.redia9;
                break;
            case 9:
                redia = R.raw.redia10;
                break;
            case 10:
                redia = R.raw.redia11;
                break;
            case 11:
                redia = R.raw.redia12;
                break;
            case 12:
                redia = R.raw.redia13;
                break;
            case 13:
                redia = R.raw.redia14;
                break;
            case 14:
                redia = R.raw.redia15;
                break;
            case 15:
                redia = R.raw.redia16;
                break;
            case 16:
                redia = R.raw.redia17;
                break;
            case 17:
                redia = R.raw.redia18;
                break;
            case 18:
                redia = R.raw.redia19;
                break;
            case 19:
                redia = R.raw.redia20;
                break;
            case 20:
                redia = R.raw.redia21;
                break;
            case 21:
                redia = R.raw.redia22;
                break;
            case 22:
                redia = R.raw.redia23;
                break;
            case 23:
                redia = R.raw.redia24;
                break;
            case 24:
                redia = R.raw.redia25;
                break;
            case 25:
                redia = R.raw.redia26;
                break;
            case 26:
                redia = R.raw.redia27;
                break;
            case 27:
                redia = R.raw.redia28;
                break;
            case 28:
                redia = R.raw.redia29;
                break;
            case 29:
                redia = R.raw.redia30;
                break;
            case 30:
                redia = R.raw.redia31;
                break;
            case 31:
                redia = R.raw.redia32;
                break;
            case 32:
                redia = R.raw.redia33;
                break;
            case 33:
                redia = R.raw.redia34;
                break;
            case 34:
                redia = R.raw.redia35;
                break;
            case 35:
                redia = R.raw.redia36;
                break;
            case 36:
                redia = R.raw.redia37;
                break;
            case 37:
                redia = R.raw.redia38;
                break;
            case 38:
                redia = R.raw.redia39;
                break;
            case 39:
                redia = R.raw.redia40;
                break;
            case 40:
                redia = R.raw.redia41;
                break;
            case 41:
                redia = R.raw.redia42;
                break;
            case 42:
                redia = R.raw.redia43;
                break;
            case 43:
                redia = R.raw.redia44;
                break;
            case 44:
                redia = R.raw.redia45;
                break;
        }
        return redia;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopPlay();
        stopRecord();
        ErrSelectedSingle.getInstance().clearList();
        ErrIdSelectedSingle.getInstance().clearList();
    }

    @Override
    protected void onPause() {
        super.onPause();
        stopPlay();
        stopRecord();
//        ErrSelectedSingle.getInstance().clearList();
//        ErrIdSelectedSingle.getInstance().clearList();
    }

    //停止播放
    private void stopPlay() {
        //停止播放
        if (player != null) {
            if (isPlay) {
                player.stop();
                player = null;
            }
        }
        if (audioText != null) {
            audioText.stop();
            audioText = null;
        }

        media1 = null;

        if (audioPlayer != null) {
            audioPlayer.stop();
            audioPlayer = null;
        }
    }

    @Override
    public void showResult(int type) {
        if (type == 1) {
            submitTime = Mutils.getTimeStame();
            String time = Mutils.formatTime(submitTime - nowTime);
            if (time.equals("0")) {
                time = "1";
            }
            Intent intent = new Intent(SimulationExerciseActivity.this, QuestionResultActivity.class);
            Log.d("sunyan", "答题记录" + ErrIdSelectedSingle.getInstance().getWorksList().toString());
            intent.putIntegerArrayListExtra("info", (ArrayList<Integer>) ErrIdSelectedSingle.getInstance().getWorksList());
            intent.putExtra("time", time);
            startActivity(intent);
        }

        this.finish();
    }

    @Override
    public void show401() {

    }

    //倒计时
    class TimeCount extends CountDownTimer {

        TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            longNow = new BigDecimal(millisUntilFinished).divide(new BigDecimal(1000), 1, BigDecimal.ROUND_UP);
        }

        @Override
        public void onFinish() {

        }
    }

    //录音
    @SuppressLint("HandlerLeak")
    private void startRecord() {
        filePath = FileUtils.getAppPath();
        File file = new File(filePath);
        if (!file.exists()) {
            if (!file.mkdirs()) {
                Toast.makeText(getContext(), "创建文件失败", Toast.LENGTH_SHORT).show();
                return;
            }
        }

        filePath = FileUtils.getAppPath() + UUID.randomUUID().toString() + ".mp3";
        mRecorder = new MP3Recorder(new File(filePath));

        mRecorder.setErrorHandler(new Handler() {
            @SuppressLint("HandlerLeak")
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.what == MP3Recorder.ERROR_TYPE) {
                    Toast.makeText(getContext(), "没有麦克风权限", Toast.LENGTH_SHORT).show();
                    resolveError();
                }
            }
        });

        try {
            mRecorder.start();
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(getContext(), "录音出现异常", Toast.LENGTH_SHORT).show();
            resolveError();
            return;
        }
    }

    /**
     * 录音异常
     */
    private void resolveError() {
        FileUtils.deleteFile(filePath);
        filePath = "";
        if (mRecorder != null && mRecorder.isRecording()) {
            mRecorder.stop();
        }
    }

    //停止录音
    private void stopRecord() {
        if (mRecorder != null && mRecorder.isRecording()) {
            mRecorder.setPause(false);
            mRecorder.stop();
        }
    }

    /**
     * 播放
     */
    @SuppressLint("HandlerLeak")
    private void playInModeStream() {
        if (TextUtils.isEmpty(filePath) || !new File(filePath).exists()) {
            Toast.makeText(SimulationExerciseActivity.this, "文件不存在", Toast.LENGTH_SHORT).show();
            return;
        }
        audioPlayer = new AudioPlayer(SimulationExerciseActivity.this, new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case AudioPlayer.HANDLER_CUR_TIME://更新的时间

                        break;
                    case AudioPlayer.HANDLER_COMPLETE://播放结束

                        break;
                    case AudioPlayer.HANDLER_PREPARED://播放开始

                        break;
                    case AudioPlayer.HANDLER_ERROR://播放错误

                        break;
                }

            }
        });

        audioPlayer.playUrl(filePath);
    }

    private void showAnimation(String str) {
        rlAnswer.setVisibility(View.VISIBLE);
        tvAnswer.setText(str);
        int screenWidth = ScreenUtils.getScreenWidth(this);//获取屏幕宽度
        translateAnimation = new TranslateAnimation(-800, 0, 0, 0);//设置平移的起点和终点
        translateAnimation.setDuration(1000);//动画持续的时间为10s
        translateAnimation.setFillEnabled(true);//使其可以填充效果从而不回到原地
        translateAnimation.setFillAfter(true);//不回到起始位置
//如果不添加setFillEnabled和setFillAfter则动画执行结束后会自动回到远点
//        translateAnimation.setAnimationListener(this);
        rlAnswer.setAnimation(translateAnimation);//给imageView添加的动画效果
        translateAnimation.startNow();//动画开始执行 放在最后即可
    }

    //退出
    private void showSingleOut() {
        final SingleOutPopup popup = new SingleOutPopup(SimulationExerciseActivity.this, 2);
        popup.setPopupWindowFullScreen(true);
        popup.showPopupWindow();
        popup.setModeListener(new LoginOutPopup.IModeSelection() {
            @Override
            public void getMode(int mode) {
                if (mode == 1) { //确定退出
//                    submitTime = Mutils.getTimeStame();
//                    String time = Mutils.formatTime(submitTime - nowTime);
//                    if (time.equals("0")) {
//                        time = "1";
//                    }
//                    if (!JsonParseUtil.ListToStr(ErrSelectedSingle.getInstance().getWorksList()).equals("") || !JsonParseUtil.ListToStr(ErrIdSelectedSingle.getInstance().getWorksList()).equals("")) {
//                        errorQuestionPresenter.setErrorQuestion(
//                                2,
//                                college_id,
//                                question_rank_id,
//                                question_class_id,
//                                JsonParseUtil.ListToStr(ErrSelectedSingle.getInstance().getWorksList()),
//                                JsonParseUtil.ListToStr(ErrIdSelectedSingle.getInstance().getWorksList()),
//                                time);
//                    }
                    popup.dismiss();
                    stopPlay();
                    SimulationExerciseActivity.this.finish();
                } else if (mode == 2) {
                    popup.dismiss();
                }
            }
        });
    }

    @SuppressLint("HandlerLeak")
    private void play(String bg_sound) {
        player = new AudioPlayer(SimulationExerciseActivity.this, new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case AudioPlayer.HANDLER_CUR_TIME://更新的时间
                        break;
                    case AudioPlayer.HANDLER_COMPLETE://播放结束
                        isPlayFinish = true;
                        isPlay = false;
                        ivPlay.setImageResource(R.mipmap.bofang);
                        break;
                    case AudioPlayer.HANDLER_PREPARED://播放开始
                        isPlayFinish = false;
                        isPlay = true;
                        ivPlay.setImageResource(R.mipmap.zanting);
                        break;
                    case AudioPlayer.HANDLER_ERROR://播放错误
                        break;
                }
            }
        });
        player.playUrl(Constant.IMAGE_HEAD + bg_sound);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (KeyEvent.KEYCODE_BACK == keyCode && KeyEvent.ACTION_DOWN == event.getAction()) {
            showSingleOut();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}
